#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append(r'E:\\TQPY\\')
from  tq_py.strategy import Strategy
from tq_py.config import Config
import copy
import time
import decimal
import pandas as pd
from tqsdk import TqApi, TqAuth, TargetPosTask,TqKq
import numpy as np
from datetime import datetime
import yaml
from tqsdk.ta import BOLL

class Aberration(Strategy):
    def __init__(self,dict_cfg):
        super().__init__(dict_cfg)



    # 使用BOLL指标计算中轨、上轨和下轨，其中26为周期N  ，2为参数p
    def boll_line(self,klines):
        boll = BOLL(klines, 26, 2)
        midline = boll["mid"].iloc[-1]
        topline = boll["top"].iloc[-1]
        bottomline = boll["bottom"].iloc[-1]
        #print(self.stra_name+" 策略运行，中轨：%.2f，上轨为:%.2f，下轨为:%.2f" % (midline, topline, bottomline))
        return midline, topline, bottomline
    def boll_line_plot(self,klines):
        boll = BOLL(klines, 26, 2)
        midline = boll["mid"]
        topline = boll["top"]
        bottomline = boll["bottom"]
        #print("策略运行，中轨：%.2f，上轨为:%.2f，下轨为:%.2f" % (midline, topline, bottomline))
        return midline, topline, bottomline

    def stra(self):
        self.midline, self.topline, self.bottomline = self.boll_line(self.klines)
        midline, topline, bottomline = self.boll_line_plot(self.klines)
        self.klines['midline'] = midline
        self.klines['topline'] = topline
        self.klines['bottomlne'] =bottomline

        while True:

            self.api.wait_update()
            # 每次生成新的K线时重新计算BOLL指标
            #print(self.stra_name)

            if self.api.is_changing(self.klines.iloc[-1], "datetime"):
                self.midline, self.topline, self.bottomline = self.boll_line(self.klines)
                midline, topline, bottomline = self.boll_line_plot(self.klines)
                self.klines['midline'] = midline
                self.klines['topline'] = topline
                self.klines['bottomlne'] = bottomline

            # 每次最新价发生变化时进行判断
            if self.api.is_changing(self.klines.iloc[-1], "close"):
                # 判断开仓条件

                if self.MarketPosition==0:
                    # 如果最新价大于上轨，K线上穿上轨，开多仓
                    if self.klines.close.iloc[-1] > self.topline:
                        print(self.stra_name+" K线上穿上轨，开多仓")
                        self.buy()
                    # 如果最新价小于轨，K线下穿下轨，开空仓
                    elif self.klines.close.iloc[-1] < self.bottomline:
                        print(self.stra_name+" K线下穿下轨，开空仓")
                        self.sellshort()
                    else:
                        #print("当前最新价%.2f,未穿上轨或下轨，不开仓" %self.klines.close.iloc[-1] )
                        pass


                # 在多头情况下，空仓条件
                elif self.MarketPosition > 0:
                    # 如果最新价低于中线，多头清仓离场
                    if self.klines.close.iloc[-1] < self.midline:
                        print(self.stra_name+" 最新价低于中线，多头清仓离场")
                        self.sell()
                    else:
                        pass
                        #print("当前多仓，未穿越中线，仓位无变化")


                # 在空头情况下，空仓条件
                elif self.MarketPosition < 0:
                    # 如果最新价高于中线，空头清仓离场
                    if self.klines.close.iloc[-1] > self.midline:
                        print(self.stra_name+" 最新价高于中线，空头清仓离场")
                        self.buytocover()
                    else:
                        pass
                        #print("当前空仓，未穿越中线，仓位无变化")
        self.api.close()


